package com.yang.sso.oauth2.security;

import cn.hutool.core.collection.CollectionUtil;
import com.yang.sso.oauth2.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;


/**
 * @author: lslands
 * @version: 1.0
 * @create: 2024/5/12
 * @description:
 */
@Slf4j
@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class SecurityConfig  extends SecurityProperties {


    /**
     * 用户安全策略
     * @param http http
     * @param introspector 入参
     * @return SecurityFilterChain
     * @author lslands
     * @date 2024/5/12 14:06
     */
    @Bean
    @Order(5)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector)
            throws Exception {
        //Mvc请求匹配器
        MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
        http.authorizeHttpRequests((requests) -> {
                            if (CollectionUtil.isNotEmpty(super.getWhitePaths())) {
                                for (String whitelistPath : super.getWhitePaths()) {
                                    requests.requestMatchers(mvcMatcherBuilder.pattern(whitelistPath)).permitAll();
                                }
                            }
                            requests.anyRequest().authenticated();
                        }
                )
                .csrf(AbstractHttpConfigurer::disable)
                .formLogin(Customizer.withDefaults());
        log.info("Seurity放行路由:{}",super.getWhitePaths());
        return http.build();
    }
}
